package com.orangelife.mobile.tehui;

import android.content.Context;
import android.graphics.Bitmap;
import android.os.Bundle;
import android.support.annotation.Nullable;
import android.support.v4.widget.SwipeRefreshLayout;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.view.WindowManager;
import android.widget.AdapterView;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.RelativeLayout;
import android.widget.TextView;

import com.common.jump.WebJumper;
import com.common.sp.AppSp;
import com.curry.android.http.OrangeDataHandler;
import com.curry.android.http.OrangeErrorHandler;
import com.curry.android.http.VolleyHttpUtil;
import com.curry.android.util.CountDownHMSHandler;
import com.curry.android.util.IntentHelper;
import com.curry.android.util.StringUtil;
import com.curry.android.util.ToastHelper;
import com.curry.orangelife.mobile.R;
import com.nostra13.universalimageloader.core.DisplayImageOptions;
import com.nostra13.universalimageloader.core.ImageLoader;
import com.nostra13.universalimageloader.core.display.RoundedBitmapDisplayer;
import com.orangelife.mobile.common.fragment.OrangeLifeBaseFragment;
import com.common.jump.TeHuiJumper;
import com.common.sp.UserSp;
import com.orangelife.mobile.common.view.EmptyLayout;
import com.orangelife.mobile.widget.ScrollGridView;

import org.json.JSONObject;

import java.util.ArrayList;
import java.util.List;
import java.util.Map;

import butterknife.Bind;
import butterknife.ButterKnife;
import butterknife.OnClick;

/**
 * 特惠，主页第二个节目
 * <p/>
 * Modify by wgf on 160713.
 *
 * @author yw
 */
public class TeHuiFragment2 extends OrangeLifeBaseFragment {
    @Bind(R.id.gvGoods)
    ScrollGridView gvGoods;
    @Bind(R.id.tvTipTime)
    TextView tvTipTime;
    @Bind(R.id.tvHour)
    TextView tvHour;
    @Bind(R.id.tvMinute)
    TextView tvMinute;
    @Bind(R.id.tvSecond)
    TextView tvSecond;
    @Bind(R.id.tvRemark)
    TextView tvRemark;
    @Bind(R.id.ivNext)
    ImageView ivNext;
    @Bind(R.id.emptyLayout)
    EmptyLayout emptyLayout;
    @Bind(R.id.rl_statusbar)
    RelativeLayout rlStatusbar;
    @Bind(R.id.llNext)
    LinearLayout llNext;
    @Bind(R.id.ivTopAD)
    ImageView ivTopAD;
    @Bind(R.id.swipeRefresh)
    SwipeRefreshLayout swipeRefresh;
    @Bind(R.id.ivSignIn)
    ImageView ivSignIn;
    private GoodsGridAdapter adapter;
    List<Map<String, Object>> list;
    CountDownHMSHandler countDownHandler;
    private int defaltTime = 61;
    private View homePageView;
    private String activityID;
    private String nextActivityID;
    private int status;
    private Bundle bundle;
    private boolean hidden = false;//是否隐藏头部
    private WindowManager wm;
    /** 是否被销毁 */
    private boolean isDestroyView;

    @Override
    public void onCreate(@Nullable Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setRetainInstance(true);
        bundle = getArguments();
        if (bundle != null) {
            activityID = bundle.getString("activityID");
            hidden = true;
        }
    }

    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container,
                             Bundle savedInstanceState) {
        isDestroyView = false;
        if (homePageView == null) {
            homePageView = inflater.inflate(R.layout.fragment_te_hui, container, false);
            ButterKnife.bind(this, homePageView);
            isConnected();
            wm = (WindowManager) getActivity().getSystemService(Context.WINDOW_SERVICE);
            initView();
            setGvAdapter();
            requestData();
            showSignIn(null);
        } else {
            ButterKnife.bind(this, homePageView);
        }
        clearChildView(homePageView);
        return homePageView;
    }

    private void showSignIn(ImageView view) {
        if (view == null) {
            view = ivSignIn;
        }
        if (UserSp.hasSign()) {
            view.setImageResource(R.drawable.ic_sign_in);
        } else {
            view.setImageResource(R.drawable.ic_sign_in_red);
        }
    }

    private void initView() {
        if (hidden) {
            rlStatusbar.setVisibility(View.GONE);
        }
        swipeRefresh.setOnRefreshListener(new SwipeRefreshLayout.OnRefreshListener() {
            @Override
            public void onRefresh() {
                requestData();
            }
        });
        emptyLayout.setOnLayoutClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                requestData();
            }
        });
    }

    @OnClick({R.id.ivNext, R.id.ivSignIn})
    public void onClick(View view) {
        switch (view.getId()) {
            case R.id.ivNext:
                if (!StringUtil.isBlank(nextActivityID)) {/*下期预告*/
                    jumpToTehuiActivity();
                }
                break;
            case R.id.ivSignIn:
                if (!UserSp.hasSign()) {/*如果红点显示，则隐藏掉，否则不处理*/
                    UserSp.setSignInDate();
                    showSignIn((ImageView) view);
                }
                jumpToSignIn(AppSp.isShowGuide());
                AppSp.setIsShowGuide(false);
                break;
        }
    }

    /**
     * 跳转到签到界面 ，并且
     */
    private void jumpToSignIn(boolean isFirstTime) {
        WebJumper.jumpToSignIn(getActivity(), isFirstTime);
    }

    private void jumpToTehuiActivity() {
        IntentHelper.getInstances().intentWithExtra(getActivity(), TehuiActivity.class, "id", nextActivityID);
    }

    private void jumpToTeHuiDetail(String activityGoodsID) {
        TeHuiJumper.jumpToTeHuiDetail(getActivity(), activityGoodsID);
    }

    private void requestData() {
        TeHuiBiz.getTehuiData(activityID, new VolleyHttpUtil.ResponseCallBack() {
            @Override
            public void handleResponse(JSONObject jsonObject, int i) {
                if (isDestroyView) {
                    return;
                }
                emptyLayout.dismiss();
                if (OrangeErrorHandler.getInstance().isSuccess(jsonObject)) {
                    Map<String, Object> map = OrangeDataHandler.getMapWithEntityNoGson(jsonObject);
                    if (map != null) {
                        initData(map);
                    } else {
                        emptyLayout.setErrorType(EmptyLayout.NODATA);
                    }
                } else {
                    emptyLayout.setErrorType(EmptyLayout.NODATA);
                }
            }
        });
    }

    private void requestRemindInfo() {
        TeHuiBiz.getRemindInfo(activityID, new VolleyHttpUtil.ResponseCallBack() {
            @Override
            public void handleResponse(JSONObject jsonObject, int i) {
                if (OrangeErrorHandler.getInstance().isSuccess(jsonObject)) {
                    ToastHelper.getInstance().displayToastWithQuickClose("开抢提醒设置成功");
                } else {
                    ToastHelper.getInstance().displayToastWithQuickClose("开抢提醒设置失败");
                }
            }
        });
    }

    private void setGvAdapter() {
        list = new ArrayList<>();
        adapter = new GoodsGridAdapter(list, getActivity());
        gvGoods.setAdapter(adapter);
        gvGoods.setOnItemClickListener(new AdapterView.OnItemClickListener() {
            @Override
            public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
                if (list != null && list.size() > 0) {
                    jumpToTeHuiDetail(String.valueOf(list.get(position).get("activityGoodsID")));
                }
            }
        });
        //回调 1.购买 2.短信提醒
        adapter.setInf(new GoodsGridAdapter.TehuiInf() {
            @Override
            public void buy(Map<String, Object> map) {
                if (map != null && list.size() > 0) {
                    jumpToTeHuiDetail(String.valueOf(map.get("activityGoodsID")));
                }
            }

            @Override
            public void remind(Map<String, Object> map) {
                requestRemindInfo();
            }
        });
        gvGoods.setFocusable(false);
    }

    private void initData(Map<String, Object> map) {
        list = (List<Map<String, Object>>) map.get("activityGoods");
        nextActivityID = String.valueOf(map.get("nextActivityID"));//下期预告ID
        activityID = String.valueOf(map.get("activityID"));
        defaltTime = (int) Double.parseDouble(String.valueOf(map.get("leftTime")));
        status = Integer.parseInt(String.valueOf(map.get("status")));
        String startTime = String.valueOf(map.get("startTime"));
        String potoUrl = String.valueOf(map.get("potoUrl"));
        String remak = String.valueOf(map.get("remak"));//规则说明
        String activityNumber = String.valueOf(map.get("activityNumber"));
        String endTime = String.valueOf(map.get("endTime"));
        String activityName = String.valueOf(map.get("activityName"));
        String nextpotoUrl = String.valueOf(map.get("nextpotoUrl"));
        if (wm == null) {
            wm = (WindowManager) getActivity().getSystemService(Context.WINDOW_SERVICE);
        }
        int width = wm.getDefaultDisplay().getWidth();
        int height = width * 9 / 16;
        LinearLayout.LayoutParams params = new LinearLayout.LayoutParams(width, height);
        if (ivTopAD == null) {
            ButterKnife.bind(this, homePageView);
            initView();
        }
        ivTopAD.setLayoutParams(params);
        ivNext.setLayoutParams(params);
        ivTopAD.setPadding(14, 14, 14, 14);
        ivNext.setPadding(14, 14, 14, 14);
        tvRemark.setText(remak);
        DisplayImageOptions options;
        options = new DisplayImageOptions.Builder()
                .showImageOnLoading(R.drawable.shop_header)
                .showImageForEmptyUri(R.drawable.shop_header)
                .showImageOnFail(R.drawable.shop_header)
                .cacheInMemory(true)
                .cacheOnDisk(true)
                .considerExifParams(true)
                .bitmapConfig(Bitmap.Config.RGB_565)
                .displayer(new RoundedBitmapDisplayer(10))
                .build();
        ImageLoader.getInstance().displayImage(potoUrl, ivTopAD, options);
        if (status == 0) {
            tvTipTime.setText(getActivity().getResources().getString(R.string.activity_time_tip_start));
        } else {
            tvTipTime.setText(getActivity().getResources().getString(R.string.activity_time_tip_end));
        }
        if (StringUtil.isBlank(nextActivityID)) {
            llNext.setVisibility(View.GONE);
        } else {
            ImageLoader.getInstance().displayImage(nextpotoUrl, ivNext, options);
        }
        adapter.setList(list);
        adapter.setStatus(status);
        adapter.notifyDataSetChanged();
        startTimeDown();
    }


    /**
     * 开启倒计时
     */
    private void startTimeDown() {
        if (countDownHandler == null) {
            countDownHandler = new CountDownHMSHandler(tvHour, tvMinute, tvSecond, 0);
            countDownHandler.setOnCountDownTimerFinishedListener(new CountDownHMSHandler.OnCountDownTimerFinishedListener() {
                @Override
                public void onFinish() {
                    requestData();
                }

                @Override
                public void onCountDown(int h, int m, int s) {
                }

            });
            countDownHandler.startTimer(defaltTime);
        } else {
            countDownHandler.stopTimer();
            countDownHandler = null;
            startTimeDown();
        }
    }


    @Override
    public void onDestroy() {
        super.onDestroy();
        if (countDownHandler != null)
            countDownHandler.stopTimer();
    }

    @Override
    public void onDestroyView() {
        super.onDestroyView();
        isDestroyView = true;
        ButterKnife.unbind(this);
    }

}
